package com.pptv.ads.core.register;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

import com.pptv.ads.core.Register;

/**
 * 
 * @author junjiechen
 *
 */

public abstract class ZKRegister  implements Register {
	
	public final static String CLIENT_PATH = "/client";
	public final static String CLIENT_LISTENER_PATH = "/client/event";
	
	public final static String ZK_EVENT_PATH = "/event";
	
	protected String host;
	protected String leaderPath;
	protected CuratorFramework client;
	private LeaderLatch leaderLatch;
	
	public ZKRegister(String host,String leaderPath) {
		this.host = host;
		this.leaderPath = leaderPath;
	}
	
	public void doRegister() throws Exception {
		client = CuratorFrameworkFactory.builder()
				.connectString(host).sessionTimeoutMs(10000)
				.connectionTimeoutMs(10000).canBeReadOnly(false)
				.retryPolicy(new ExponentialBackoffRetry(1000, 3))
				.defaultData(null).build();
		client.start();
		leaderLatch = new LeaderLatch(client, leaderPath);
		leaderLatch.addListener(new LeaderLatchListener() {
			public void isLeader() {
				beLeader();
			}
			
			public void notLeader() {
				notBeLeader();
			}
		});
		beforeSelect();
		leaderLatch.start();
		
	}

	
	public String getLeaderPath(){
		return leaderPath;
	}
	
	public void beforeSelect(){
		
	}

	
}
